package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.NewsDao;
import com.cn.wanxi.model.NavModel;
import com.cn.wanxi.model.NewsModel;
import com.cn.wanxi.service.NewsService;
import com.cn.wanxi.util.FileNames;
import com.cn.wanxi.util.IOTool;
import com.cn.wanxi.util.Tool;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class NewsServiceImpl implements NewsService {
    @Override
    public NewsModel[] getNewsModelsForHomePage() {
        //1.创建文件
        IOTool.createFile(FileNames.FILE_NAME_NEWS);
//        2.写入数据
        List<String> data = getData();
        IOTool.writeData(data);
//        3.读取数据
        String s = IOTool.readData();
//        4.封装数据
        return setData(s);
    }

    private NewsModel[] setData(String result) {
        System.out.println(result);
        String[] results = result.split(FileNames.SPLIT);
        String href = results[0];
        href = Tool.replaceKuiHao(href);
        String title = results[1];
        title = Tool.replaceKuiHao(title);
        String[] hrefs = {};
        hrefs = href.split(", ");
        String[] titles = title.split(", ");
        int length = hrefs.length;
        NewsModel[] newsModels = new NewsModel[length];
        for (int i = 0; i < length; i++) {
            NewsModel newsModel = new NewsModel();
            newsModel.setTitle(titles[i]);
            newsModel.setHref(hrefs[i]);
            newsModels[i] = newsModel;
        }
        return newsModels;
    }

    private List<String> getData() {
        List<String> list = new ArrayList<>();
        NewsDao newsDao = new NewsDao();
        list.add(Arrays.toString(newsDao.titlesForHomePage));

        return list;
    }
}
